package com.chaodev.base.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.chaodev.base.dao.CommDao;
import com.chaodev.base.dao.UserDao;
import com.chaodev.base.dao.VolunteerDao;
import com.chaodev.base.em.BizTypeEnum;
import com.chaodev.base.em.OperEnum;
import com.chaodev.base.model.*;
import com.chaodev.base.service.VolunteerService;
import com.chaodev.base.utils.CodeGenerateUtil;
import com.chaodev.base.utils.MD5Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

@Service
public class VolunteerServiceImpl implements VolunteerService {
    @Autowired
    private VolunteerDao volunteerDao;

    @Autowired
    private CommDao commDao;

    @Autowired
    private UserDao userDao;


    @Override
    public PageInfo<Volunteer> queryPageList(Integer page, Integer rows, Volunteer volunteer) {
        PageHelper.startPage(page, rows);
        List<Volunteer> tbVolunteerList = volunteerDao.queryDataList(volunteer);
        PageInfo<Volunteer> pageInfo = new PageInfo<Volunteer>(tbVolunteerList, rows);
        return pageInfo;
    }

    @Override
    public Volunteer findDataById(Integer id) {
        return volunteerDao.findDataById(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveData(Volunteer volunteer, UserInfo userInfo) throws DataAccessException {
        if (ObjectUtil.isNotNull(volunteer.getId()) && volunteer.getId() > 0) {
            volunteerDao.updateDataById(volunteer);
        } else {
            volunteer.setUserId(volunteer.getRealAccNbr());
            //生成志愿者编号,并判断是否重复
            String volunteerId = getVolunteerId();

            volunteer.setVolunteerId(volunteerId);
            volunteerDao.insertData(volunteer);
            Map<String, Object> userMap = new HashMap<>();
            userMap.put("P_USER_ID", volunteer.getRealAccNbr());
            String s = null;
            try {
                s = MD5Util.md5Encode("000000").toUpperCase(Locale.ROOT);
            } catch (Exception e) {
                e.printStackTrace();
            }
            userMap.put("P_PASSWORD", s);
            userMap.put("P_USER_NAME", volunteer.getUserName());
            userMap.put("P_REAL_ACC_NBR", volunteer.getRealAccNbr());
            userMap.put("U_USER_ID", "admin");
            userMap.put("P_ROLE_ID", 1315);
            userMap.put("P_DEPART_ID", "67449901");
            userMap.put("P_EMAIL", volunteer.getEmail());
            int i = userDao.lookUser(userMap);
            if (i == 0) {
                userDao.userAdd(userMap);
                userDao.userDepartAdd(userMap);
            }

            ApplyLc applyLc = new ApplyLc();
            applyLc.setBizType(BizTypeEnum.Em_Volunteer.getValue());
            applyLc.setBizId(volunteer.getId());
            applyLc.setReqState(1);
            applyLc.setLcId("lc_001");
            applyLc.setResultCode(OperEnum.Em_Add.getValue());
            applyLc.setResultDsc(OperEnum.Em_Add.getName());
            applyLc.setOpr(userInfo.getUserId());
            applyLc.setOpTime(new Date());
            applyLc.setState(2);
            commDao.saveApply(applyLc);

            ApplyStateToNext stateToNext = new ApplyStateToNext();
            stateToNext.setBizType(BizTypeEnum.Em_Volunteer.getValue());
            stateToNext.setReqState(1);
            stateToNext.setNowLcId("lc_001");
            stateToNext.setOp(OperEnum.Em_Add.getValue());
            ApplyStateToNext nextFlowInfo = commDao.getNextFlowInfo(stateToNext);

            Task task = new Task();
            task.setBizType(BizTypeEnum.Em_Volunteer.getValue());
            task.setTitle("志愿者申请");
            task.setBizId(volunteer.getId());
            task.setLcId(nextFlowInfo.getNextLcId());
            task.setLcName(nextFlowInfo.getNextLcName());
            task.setCUser(userInfo.getUserId());
            task.setState(1);
            commDao.saveTask(task);

            applyLc = new ApplyLc();
            applyLc.setBizType(BizTypeEnum.Em_Volunteer.getValue());
            applyLc.setBizId(volunteer.getId());
            applyLc.setReqState(1);
            if (StrUtil.isNotEmpty(nextFlowInfo.getNextLcId())) {
                applyLc.setLcId(nextFlowInfo.getNextLcId());
            }
            applyLc.setState(1);
            commDao.saveApply(applyLc);
        }
    }


    private String getVolunteerId() {
        String volunteerId = CodeGenerateUtil.getNewEquipmentNoByTime(CodeGenerateUtil.PRE_VOLUNTEER_CODE);
        Volunteer volunteer1 = volunteerDao.selectByVolunteerId(volunteerId);
        if (volunteer1 != null) {
            getVolunteerId();
        }
        return volunteerId;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteDataById(List<Integer> ids) throws DataAccessException {
        volunteerDao.deleteDataById(ids);
    }

    @Override
    public Map<String, Object> getVolunteerStatistic(String userId) {
        LinkedHashMap<String, Object> resultActivity = volunteerDao.selectVolunteerActivityStatistic(userId);
        LinkedHashMap<String, Object> resultTrain = volunteerDao.selectVolunteerTrainStatistic(userId);
        Map<String, Object> resultMap = new HashMap<>(5);
        resultMap.put("activityNum", resultActivity.get("activityNum"));
        resultMap.put("activityTime", resultActivity.get("activityTime"));
        resultMap.put("trainingCount", resultTrain.get("trainingCount"));
        resultMap.put("trainingItemNum", resultTrain.get("trainingItemNum"));
        resultMap.put("points", resultTrain.get("points"));
        resultMap.put("trainTime", resultTrain.get("trainTime"));
        resultMap.put("level", Integer.parseInt(null == resultTrain.get("points") ? "0" : resultTrain.get("points").toString()) / 100 + 1);
        return resultMap;
    }

    @Override
    public List<Volunteer> queryDataList(Volunteer volunteer) {
        return volunteerDao.queryDataList(volunteer);
    }

    @Override
    public Volunteer findDataByUserId(String userId) {
        return volunteerDao.selectData(userId);
    }
}
